package org.blogwu.learn.leetcode.链表;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int x) { val = x; }
 * }
 */
public class _206_反转链表_迭代 {

    public static void main(String[] args) {
        ListNode listNode5 = new ListNode(5);
        ListNode listNode4 = new ListNode(4, listNode5);
        ListNode listNode3 = new ListNode(3, listNode4);
        ListNode listNode2 = new ListNode(2, listNode3);
        ListNode listNode1 = new ListNode(1, listNode2);
        System.out.println(listNode1.toString());
        _206_反转链表_迭代 ff = new _206_反转链表_迭代();

        ListNode listNodeNew = ff.reverseList(listNode1);
        System.out.println(listNodeNew.toString());
    }


    //  1(2) >> 2(3) >> 3(4) >> 4(5) >> 5(null)
    //  1(null) << 2(1) << 3(2) << 4(3) << 5(4)

    /**
     * 思路：每一次迭代都需要 保存 current 和 next,当next为NUll是就当了最后的节点了
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode pre = null;

        while (head != null) {
            ListNode temp = head.next;
            head.next = pre;
            pre = head;
            head = temp;
        }
        return pre;
    }

}
